﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.Const;
using FBroSharp.DataType;
using FBroSharp.Event;
using System.Threading;

namespace _3_自动登录浏览器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "auto_login_browser";
        private IFBroSharpBrowser _browser;
        private bool _isAutoLoggingIn = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建浏览器控件
            CreateBrowser();
        }

        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息
                FBroSharpWindowsInfo windows_info = new FBroSharpWindowsInfo
                {
                    parent_window = this.Handle,
                    x = 0,
                    y = 0,
                    width = this.Width,
                    height = this.Height,
                    window_name = "自动登录浏览器"
                };

                // 创建浏览器事件回调类
                BrowserEvent browser_event = new BrowserEvent(this);

                // 创建浏览器
                if (FBroSharpControl.CreatBrowser(
                    "file:///T:/Csharp/QoderMcpFBro/3-自动登录浏览器/login.html",
                    windows_info,
                    default,
                    default,
                    default,
                    browser_event,
                    default,
                    BROWSER_USER_FLAG))
                {
                    UpdateStatus("浏览器创建成功");
                }
                else
                {
                    UpdateStatus("浏览器创建失败");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"创建浏览器时出错: {ex.Message}");
            }
        }

        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateStatus), message);
                return;
            }

            // 这里可以更新状态栏或标签控件
            Console.WriteLine(message);
        }

        public void UpdateNavigationButtons()
        {
            // 更新导航按钮状态
        }

        public void PerformAutoLogin()
        {
            // 防止重复执行自动登录
            if (_isAutoLoggingIn) return;
            _isAutoLoggingIn = true;

            // 在新线程中执行自动登录，避免阻塞UI
            Task.Run(async () =>
            {
                try
                {
                    UpdateStatus("开始自动登录流程...");

                    // 等待页面元素加载
                    await WaitForElement("#username", 10000);

                    // 填写用户名
                    FillInput("#username", "admin");
                    UpdateStatus("已填写用户名");

                    // 填写密码
                    FillInput("#password", "123456");
                    UpdateStatus("已填写密码");

                    // 点击登录按钮
                    ClickElement(".login-btn");
                    UpdateStatus("已点击登录按钮");

                    // 等待登录结果
                    await Task.Delay(2000);

                    UpdateStatus("自动登录流程完成");
                }
                catch (Exception ex)
                {
                    UpdateStatus($"自动登录失败: {ex.Message}");
                }
                finally
                {
                    _isAutoLoggingIn = false;
                }
            });
        }

        private async Task WaitForElement(string selector, int timeoutMs)
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)
            {
                throw new Exception("浏览器实例无效");
            }

            // 使用MCP工具等待元素
            // 这里我们模拟等待，实际应用中应该使用fbro_wait_for_element工具
            await Task.Delay(1000);
        }

        private void FillInput(string selector, string value)
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)
            {
                throw new Exception("浏览器实例无效");
            }

            // 使用MCP工具填写输入框
            // 实际应用中应该调用fbro_fill_input工具
            // 这里我们通过执行JavaScript来模拟
            string script = $"document.querySelector('{selector}').value = '{value}';";
            ExecuteJavaScript(script);
        }

        private void ClickElement(string selector)
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)
            {
                throw new Exception("浏览器实例无效");
            }

            // 使用MCP工具点击元素
            // 实际应用中应该调用fbro_click_element工具
            // 这里我们通过执行JavaScript来模拟
            string script = $"document.querySelector('{selector}').click();";
            ExecuteJavaScript(script);
        }

        private void ExecuteJavaScript(string script)
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)
            {
                throw new Exception("浏览器实例无效");
            }

            var frame = browser.GetMainFrame();
            if (frame != null)
            {
                frame.ExecuteJavaScript(script, "", 0);
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    // 调整浏览器大小以匹配容器
                    browser.MoveWindow(0, 0, this.Width, this.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }
    }
}